package cn.edu.xmu.oomall.customer.service;

import cn.edu.xmu.javaee.core.exception.BusinessException;
import cn.edu.xmu.javaee.core.model.ReturnNo;
import cn.edu.xmu.javaee.core.model.dto.UserDto;
import cn.edu.xmu.oomall.customer.dao.AddressDao;
import cn.edu.xmu.oomall.customer.dao.bo.Address;
import cn.edu.xmu.oomall.customer.dao.openfeign.RegionDao;
import cn.edu.xmu.oomall.customer.mapper.openfeign.Po.Region;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 谢传艳
 * @date 2024/12/19
 */
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.REQUIRED)
public class AddressService {
    private final AddressDao addressDao;
    private final RegionDao regionDao;
    /**
     * 添加地址
     * @param address 地址
     * @param user 用户
     * @return Address
     */
    public Address addAddress(Address address, UserDto user) {
        Integer addressCount = addressDao.retrieveCountByCustomerId(user.getId());
        if(addressCount >= Address.ADDRESS_MAX){
            throw new BusinessException(ReturnNo.ADDRESS_OUTLIMIT);
        }
        if(addressCount == 0){
            address.setBeDefault(Address.DEFAULT);
        }else {
            address.setBeDefault(Address.NOT_DEFAULT);
        }
        Region region = regionDao.findById(address.getRegionId());
        address.setRegion(region);
        address.setCreator(user);
        address.setCustomerId(user.getId());
        address.setGmtCreate(LocalDateTime.now());
        return addressDao.insert(address);
    }

    /**
     * 根据用户id查询地址
     * @param id 用户id
     * @return 地址列表
     */
    public List<Address> findAddressesByCustomerId(Long id) {
        List<Address> addressList = addressDao.retrieveByCustomerId(id);
        return addressList.stream().map(bo -> {
            Region region = regionDao.findById(bo.getRegionId());
            bo.setRegion(region);
            return bo;
        }).toList();
    }

    /**
     * 设置默认地址
     * @param id 地址id
     * @param user 用户
     */
    public void setDefaultAddress(Long id, UserDto user) {
        Address oldDefaultAddress = addressDao.retrieveDefaultAddressByCustomerId(user.getId());
        oldDefaultAddress.cancelDefault(user);
        Address newDefaultAddress = addressDao.findById(id);
        newDefaultAddress.setDefault(user);
    }

    /**
     * 修改地址
     * @param address 地址
     * @param user 用户
     */
    public void modifyAddress(Address address, UserDto user) {
        Address oldAddress = addressDao.findById(address.getId());
        oldAddress.modifyAddress(address, user);
    }

    /**
     * 删除地址
     * @param id 地址id
     */
    public void deleteAddress(Long id) {
        addressDao.deleteById(id);
    }
}
